package org.catpay.modules.app.controller;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.digest.DigestUtils;
import org.catpay.common.exception.RRException;
import org.catpay.common.utils.CommonMap;
import org.catpay.common.utils.R;
import org.catpay.modules.app.annotation.Login;
import org.catpay.modules.app.annotation.LoginUser;
import org.catpay.modules.app.em.UserRoleEnum;
import org.catpay.modules.app.entity.UserEntity;
import org.catpay.modules.app.service.UserService;
import org.catpay.modules.app.utils.CacheLocal;
import org.catpay.modules.app.utils.JwtUtils;
import org.catpay.modules.sys.service.SysConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import springfox.documentation.annotations.ApiIgnore;

@RestController
@RequestMapping("/app")
@Api(value = "用户controller", tags = { "用户操作接口" })

public class AppUserController {

	@Autowired
	private UserService userService;

	@Autowired
	private JwtUtils jwtUtils;
	@Autowired
	SysConfigService sysConfigService;

	/**
	 * 登录
	 */
	@PostMapping("user/login")
	@ApiOperation("登录")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "phone", value = "手机号", required = true, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "passWord", value = "密码", required = true, dataType = "String", paramType = "query") })
	public R<?> login(HttpServletRequest request, HttpServletResponse response) {

		String phone = request.getParameter("phone");
		String passWord = request.getParameter("passWord");
		Assert.hasLength(phone, "phone不能为空");
		Assert.hasLength(passWord, "passWord不能为空");
		// 用户登录
		UserEntity user = userService.login(phone, passWord);
		String token = jwtUtils.generateToken(user.getId());

		return R.ok(CommonMap.getMap().put("token", token).put("expire", jwtUtils.getExpire()).put("userInfo", user));
	}

	@PostMapping("user/register")
	@ApiOperation("注册")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "code", value = "验证码", required = true, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "recommonNumber", value = "邀请码", required = false, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "nickName", value = "昵称", required = true, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "phone", value = "手机号", required = true, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "passWord", value = "密码", required = true, dataType = "String", paramType = "query") })
	public R<?> register(HttpServletRequest request, HttpServletResponse response) {

		String recommonNumber = request.getParameter("recommonNumber");
		String phone = request.getParameter("phone");
		String passWord = request.getParameter("passWord");
		String nickName = request.getParameter("nickName");
		String code = request.getParameter("code");
		Assert.hasLength(nickName, "nickName不能为空");
		Assert.hasLength(phone, "phone不能为空");
		Assert.hasLength(passWord, "passWord不能为空");
		Assert.hasLength(code, "code不能为空");
		// 验证code

		String localcode = CacheLocal.getCode(phone);
		if (code.equals(localcode)) {
			UserEntity user = new UserEntity();
			if (recommonNumber != null) {
				UserEntity fa = userService.queryByMobile(recommonNumber);
				if (fa == null) {
					throw new RRException("推荐人不存在");
				}

				user.setFatherId(fa.getId());
				user.setFatherRecommonNumber(recommonNumber);
			}

			user.setCreateTime(new Date());
			user.setHeadImage(sysConfigService.getValue("DefaultHeadImage"));
			user.setLevel(0);
			user.setNickName(nickName);
			user.setPassword(DigestUtils.sha256Hex(passWord));
			user.setPhone(phone);
			user.setRecommonNumber(phone);
			user.setRole(UserRoleEnum.普通用户.getValue());

			userService.insert(user);
			user = userService.queryByMobile(phone);
			CacheLocal.removePhoneCode(phone);
			String token = jwtUtils.generateToken(user.getId());
			// String url = sysConfigService.getValue(SysConfig.SHAREUSERURL);
			// if(url ==null){
			// url = "";
			// }
			// String content = url+phone;
			// qiniuyunService.makeSharePage(content,"你的好友"+phone+"推荐您加入",phone);
			return R.ok(
					CommonMap.getMap().put("token", token).put("expire", jwtUtils.getExpire()).put("userInfo", user));
		} else {
			throw new RRException("验证码不正确");
		}

	}

	@PostMapping("common/sendSms")
	@ApiOperation("发送验证码")
	@ApiImplicitParams({

			@ApiImplicitParam(name = "phone", value = "手机号", required = true, dataType = "String", paramType = "query")

	})
	public R<?> sendMess(HttpServletRequest request, HttpServletResponse response) throws Exception {

		String phone = request.getParameter("phone");
		Assert.hasLength(phone, "手机号码不能为空");
		userService.sendSms(phone);

		return R.ok();
	}

	@Login
	@PostMapping("/user/getUserInfo")
	@ApiOperation("获取用户基本信息")
	public R<?> getUserInfo(@LoginUser @ApiIgnore UserEntity user, HttpServletRequest request,
			HttpServletResponse response) {

		return R.ok(CommonMap.getMap().put("userInfo", user));
	}

	// 修改密码

	@PostMapping("user/updatePassword")
	@ApiOperation("修改密码")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "code", value = "验证码", required = true, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "phone", value = "手机号", required = true, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "passWord", value = "密码", required = true, dataType = "String", paramType = "query") })
	public R<?> updatePassword(HttpServletRequest request, HttpServletResponse response) {

		String passWord = request.getParameter("passWord");
		String code = request.getParameter("code");
		String phone = request.getParameter("phone");
		Assert.hasLength(phone, "phone不能为空");
		Assert.hasLength(passWord, "passWord不能为空");
		Assert.hasLength(code, "code不能为空");
		// 验证code
		String localcode = CacheLocal.getCode(phone);
		if (code.equals(localcode)) {

			userService.updatePassword(phone, passWord);
			CacheLocal.removePhoneCode(phone);
		} else {
			throw new RRException("验证码不正确");
		}
		return R.ok();
	}

	@Login
	@PostMapping("user/setAddress")
	@ApiOperation("设置地址")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "userId", value = "userId", required = true, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "name", value = "收件人", required = true, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "phone", value = "手机号", required = true, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "province", value = "省", required = true, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "city", value = "市", required = true, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "area", value = "区", required = true, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "address", value = "地址", required = true, dataType = "String", paramType = "query") })
	public R<?> setAddress(@LoginUser @ApiIgnore UserEntity user, HttpServletRequest request,
			HttpServletResponse response) {

		String userId = request.getParameter("userId");
		String name = request.getParameter("name");
		String phone = request.getParameter("phone");
		String province = request.getParameter("province");
		String city = request.getParameter("city");
		String area = request.getParameter("area");
		String address = request.getParameter("address");
		String type = request.getParameter("type");
		Assert.hasLength(userId, "userId不能为空");
		Assert.hasLength(name, "name不能为空");
		Assert.hasLength(phone, "phone不能为空");
		Assert.hasLength(province, "province不能为空");
		Assert.hasLength(city, "city不能为空");
		Assert.hasLength(area, "area不能为空");
		Assert.hasLength(address, "address不能为空");
		Assert.hasLength(type, "type不能为空");

		return R.ok(CommonMap.getMap().put("userAddress",
				userService.setAddress(user, name, phone, province, city, area, address, type)));
	}

	@Login
	@PostMapping("user/updateAddress")
	@ApiOperation("修改设置地址")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "addressId", value = "地址ID", required = true, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "name", value = "收件人", required = true, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "phone", value = "手机号", required = true, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "province", value = "省", required = true, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "city", value = "市", required = true, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "area", value = "区", required = true, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "address", value = "地址", required = true, dataType = "String", paramType = "query") })
	public R<?> updateAddress(@LoginUser @ApiIgnore UserEntity user, HttpServletRequest request,
			HttpServletResponse response) {

		String addressId = request.getParameter("addressId");
		String name = request.getParameter("name");
		String phone = request.getParameter("phone");
		String province = request.getParameter("province");
		String city = request.getParameter("city");
		String area = request.getParameter("area");
		String address = request.getParameter("address");
		Assert.hasLength(addressId, "addressId不能为空");
		Assert.hasLength(name, "name不能为空");
		Assert.hasLength(phone, "phone不能为空");
		Assert.hasLength(province, "province不能为空");
		Assert.hasLength(city, "city不能为空");
		Assert.hasLength(area, "area不能为空");
		Assert.hasLength(address, "address不能为空");

		Long uid = Long.valueOf(addressId);

		return R.ok(CommonMap.getMap().put("userAddress",
				userService.updateAddress(user, uid, name, phone, province, city, area, address)));
	}

	@Login
	@PostMapping("user/setDefaultAddress")
	@ApiOperation("设置默认地址")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "addressId", value = "地址ID", required = true, dataType = "String", paramType = "query") })
	public R<?> setDefaultAddress(@LoginUser @ApiIgnore UserEntity user, HttpServletRequest request,
			HttpServletResponse response) {

		String addressId = request.getParameter("addressId");

		Assert.hasLength(addressId, "addressId不能为空");

		Long uid = Long.valueOf(addressId);
		userService.setDefaultAddress(user, uid);
		return R.ok();
	}

	@Login
	@PostMapping("user/getAddressList")
	@ApiOperation("获取地址")
	public R<?> getAddress(@LoginUser @ApiIgnore UserEntity user, HttpServletRequest request,
			HttpServletResponse response) {

		return R.ok(CommonMap.getMap().put("addressList", userService.getAddress(user.getId())));
	}

	/**
	 * 修改个人资料
	 * 
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@Login
	@RequestMapping("user/updateUserInfo")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "nickName", value = "nickName", required = true, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "headImage", value = "headImage", required = true, dataType = "String", paramType = "query") })
	public R<?> updateUserInfo(@LoginUser @ApiIgnore UserEntity user, HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		String nickName = request.getParameter("nickName");
		String headImage = request.getParameter("headImage");

		return R.ok(CommonMap.getMap().put("userInfo", userService.updateUserInfo(user.getId(), headImage, nickName)));
	}

	/**
	 * 上传个人头像
	 * 
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@Login
	@RequestMapping("user/updateUserHeadImage")

	public R<?> updateUserHeadImage(@LoginUser @ApiIgnore UserEntity user, HttpServletRequest request,
			HttpServletResponse response, @RequestParam("headImage") MultipartFile headImage) throws Exception {

		String userId = request.getParameter("userId");
		Assert.hasLength(userId, "userId不能为空");
		Long uid = Long.valueOf(userId);

		return R.ok(CommonMap.getMap().put("image", userService.updateUserHeadImage(uid, headImage)));
	}

}
